import socket
import threading


def receive_messages(client_socket):
    """接收服务器消息的函数"""
    while True:
        try:
            # 接收服务器发送的数据
            data = client_socket.recv(1024)
            if not data:
                print("与服务器的连接已关闭")
                break

            # 解码并打印收到的消息
            message = data.decode('utf-8')
            print(f"\n服务器回复: {message}")
            print("请输入消息: ", end='', flush=True)

        except Exception as e:
            print(f"接收消息时发生错误: {e}")
            break


def start_client(host='localhost', port=12345):
    """启动TCP客户端"""
    # 创建TCP套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 连接到服务器
        client_socket.connect((host, port))
        print(f"已连接到服务器 {host}:{port}")
        print("输入消息发送给服务器，输入 'exit' 退出")

        # 创建线程用于接收服务器消息
        receive_thread = threading.Thread(
            target=receive_messages,
            args=(client_socket,)
        )
        receive_thread.daemon = True  # 当主线程退出时，该线程也会退出
        receive_thread.start()

        # 循环发送消息给服务器
        while True:
            message = input("请输入消息: ")
            if message.lower() == 'exit':
                break

            # 发送消息到服务器
            client_socket.sendall(message.encode('utf-8'))

    except Exception as e:
        print(f"客户端发生错误: {e}")
    finally:
        # 关闭客户端套接字
        client_socket.close()
        print("客户端已关闭")


if __name__ == "__main__":
    start_client()
